package com.translate.web.api.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.param.impl.PageParam;
import com.response.vo.ResponseModel;
import com.translate.vo.ExampleVO;
import com.controller.base.AbstractCommonController;
import com.page.PageResponseData;
import com.translate.entity.Example;
import com.translate.entity.ExamplePic;
import com.translate.web.service.IExamplePicService;
import com.translate.web.service.IExampleService;
import com.basic.service.contract.IBaseService;
import com.common.util.ListConvertMap;

@RestController
@RequestMapping("example")
public class ExampleController extends AbstractCommonController<Example, PageParam> {
	private IExampleService service;
	
	private IExamplePicService examplePicService;

	public ExampleController(IExampleService service) {
		this.service = service;
	}

	@Override
	protected <VO> PageResponseData<VO> afterProcesserVO(PageResponseData<VO> orderList) {

		List<VO> data = orderList.getData();
		
		if (0 == data.size()) {
			return orderList;
		}
		examplePic((List<ExampleVO>) data);
		
		return orderList;
	}

	/**
	 * 首页案例
	 * @return
	 */
	@PostMapping("/getExamples")
	public ResponseModel<List<ExampleVO>> getExamples() {
		
		List<ExampleVO> listFromCache = this.service.getListFromCache(ExampleVO.class);
		
		if (0 == listFromCache.size()) {
			return ResponseModel.<List<ExampleVO>>success(listFromCache);
		}
		
		examplePic(listFromCache);
		
		return ResponseModel.<List<ExampleVO>>success(listFromCache);
	}

	private void examplePic(List<ExampleVO> listFromCache) {
		
		List<ExamplePic> examplePics = examplePicService.examplePics(listFromCache.stream().mapToInt(e->e.getId()).toArray());
		
		Map<Integer, List<ExamplePic>> listToMapList = ListConvertMap.listToMapList(examplePics, ExamplePic::getExampleId);
		
		List<ExamplePic> pics;
		for (ExampleVO vo : listFromCache) {
			
			pics = listToMapList.get(vo.getId());
			
			if (null == pics) {
				continue;
			}
			
			vo.setPic(pics.stream().map(e->e.getPic()).toArray(String[]::new));
		}
	}
	
	
	@Override
	protected IBaseService<Example> getBaseService() {
		return this.service;
	}

	protected <VO> Class<VO> getTarget() {
		return (Class<VO>) ExampleVO.class;
	}

	@Resource
	public void setExamplePicService(IExamplePicService examplePicService) {
		this.examplePicService = examplePicService;
	}
}